package com.kwdb.server.query;

import com.kwdb.server.storage.StorageEngine;
import com.kwdb.server.storage.KWDBStorageEngine;
import com.kwdb.grpc.QueryRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 查询引擎
 */
public class QueryEngine {
    
    private static final Logger logger = LoggerFactory.getLogger(QueryEngine.class);
    private final StorageEngine storageEngine;
    
    public QueryEngine(StorageEngine storageEngine) {
        this.storageEngine = storageEngine;
    }
    
    /**
     * 执行SQL查询
     */
    public QueryResult execute(String sql) {
        logger.info("执行查询: {}", sql);
        
        QueryResult result = new QueryResult();
        
        // 检查是否使用真实的 KWDB 数据库
        if (storageEngine instanceof KWDBStorageEngine) {
            KWDBStorageEngine kwdbEngine = (KWDBStorageEngine) storageEngine;
            
            if (kwdbEngine.isUseRealDatabase()) {
                // 使用真实数据库查询
                return executeRealQuery(sql, kwdbEngine);
            }
        }
        
        // 使用模拟数据
        return executeMockQuery(sql);
    }
    
    /**
     * 执行真实的数据库查询
     */
    private QueryResult executeRealQuery(String sql, KWDBStorageEngine kwdbEngine) {
        QueryResult result = new QueryResult();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = kwdbEngine.getDataSource().getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            
            // 获取列信息
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            
            List<String> columns = new ArrayList<>();
            for (int i = 1; i <= columnCount; i++) {
                columns.add(metaData.getColumnName(i));
            }
            result.setColumns(columns);
            
            // 获取数据行
            List<QueryRow> rows = new ArrayList<>();
            while (rs.next()) {
                QueryRow.Builder rowBuilder = QueryRow.newBuilder();
                for (int i = 1; i <= columnCount; i++) {
                    String value = rs.getString(i);
                    rowBuilder.addValues(value != null ? value : "");
                }
                rows.add(rowBuilder.build());
            }
            
            result.setSuccess(true);
            result.setMessage("查询成功");
            result.setRows(rows);
            result.setTotalCount(rows.size());
            result.setHasMore(false);
            
            logger.info("查询成功，返回 {} 行数据", rows.size());
            
        } catch (SQLException e) {
            logger.error("查询失败", e);
            result.setSuccess(false);
            result.setMessage("查询失败: " + e.getMessage());
            result.setRows(new ArrayList<>());
            result.setTotalCount(0);
            result.setHasMore(false);
        } finally {
            // 关闭资源
            if (rs != null) {
                try { rs.close(); } catch (SQLException e) { 
                    logger.error("关闭 ResultSet 失败", e); 
                }
            }
            if (stmt != null) {
                try { stmt.close(); } catch (SQLException e) { 
                    logger.error("关闭 Statement 失败", e); 
                }
            }
            if (conn != null) {
                try { conn.close(); } catch (SQLException e) { 
                    logger.error("关闭 Connection 失败", e); 
                }
            }
        }
        
        return result;
    }
    
    /**
     * 执行模拟查询（用于测试）
     */
    private QueryResult executeMockQuery(String sql) {
        QueryResult result = new QueryResult();
        result.setSuccess(true);
        result.setMessage("查询成功（模拟数据）");
        result.setColumns(Arrays.asList("measurement", "value", "timestamp"));
        
        // 返回模拟数据
        List<QueryRow> rows = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            QueryRow.Builder rowBuilder = QueryRow.newBuilder();
            rowBuilder.addValues("temperature");
            rowBuilder.addValues(String.valueOf(20 + i));
            rowBuilder.addValues(String.valueOf(System.currentTimeMillis()));
            rows.add(rowBuilder.build());
        }
        result.setRows(rows);
        result.setTotalCount(rows.size());
        result.setHasMore(false);
        
        logger.debug("返回模拟数据: {} 行", rows.size());
        
        return result;
    }
    
    /**
     * 兼容方法
     */
    public QueryResult executeQuery(String sql) {
        return execute(sql);
    }
    
    /**
     * 查询结果类
     */
    public static class QueryResult {
        private boolean success;
        private String message;
        private List<String> columns;
        private List<QueryRow> rows;
        private int totalCount;
        private boolean hasMore;
        
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
        
        public List<String> getColumns() { return columns; }
        public void setColumns(List<String> columns) { this.columns = columns; }
        
        public List<QueryRow> getRows() { return rows; }
        public void setRows(List<QueryRow> rows) { this.rows = rows; }
        
        public int getTotalCount() { return totalCount; }
        public void setTotalCount(int totalCount) { this.totalCount = totalCount; }
        
        public boolean hasMore() { return hasMore; }
        public void setHasMore(boolean hasMore) { this.hasMore = hasMore; }
    }
}

